<template>
  <div v-show="formData[key].isshow">
    <el-form-item
      :label="component.attrName"
      :id="key"
      :prop="key + '.value'"
      :required="formData[key].required.split(',').includes('empty')"
    >
      <div @click="clickHandler" class="click-wrap">
        <el-input
          v-model="formData[key].value"
          readonly
          class="hide"
        ></el-input>
        <el-input v-model="showValue" readonly>
          <template slot="append">
            <a href="javascript:;">
              <i class="el-icon-more"></i>
            </a>
          </template>
        </el-input>
      </div>
    </el-form-item>
    <el-dialog
      :title="component.attrName"
      :visible.sync="show"
      width="70"
      :withHeader="false"
      class="m-dialog"
      append-to-body
    >
      <div v-loading="loading">
        <div class="empty" v-if="loading"></div>
        <template v-else>
          <content-list
            v-bind="$attrs"
            v-on="$listeners"
            :pageInfo="pageInfo"
            :content="config.dialogContent"
            @load="load"
            @getrow="getrow"
          ></content-list>
        </template>
      </div>
    </el-dialog>
  </div>
</template>

<script>
 import ContentList from "./content-list.vue";
import http from "../../utils/http";
import { deepClone } from "../../utils/clone";
import OrderService from "@/api/order/OrderService.js";
import { mapState, mapGetters } from "vuex";
export default {
  name: "CustomerName",
  components: {
    ContentList,
  },
  data() {
    return {
      config: {},
      show: false,
      currentValue: "",
      pageInfo: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      loading: false,
      showValue: "",
    };
  },
  props: {
    component: {
      type: Object,
      default: () => {
        return {};
      },
    },
    formData: {
      type: Object,
    },
    ruleData: {
      type: Object,
    },
    actionValue: {
      type: String,
      default: "",
    },
    span: {
      type: Number || String,
      default: 16,
    },
  },
  computed: {
    ...mapState("user", ["user"]),
    ...mapState("orders", ["CUST_INFO_CHANGE"]),
 
    key() {
      return this.component.pageTempStructId + "-" + this.component.attrId;
    },
  },
  created() {
    this.dialogInputConfig();
  },

  methods: {
    //根据component的参数动态加载业务相关的配置文件
    dialogInputConfig() {
      const config = require(`./customerName.js`).default;
      this.config = deepClone(config);
    },
    clickHandler() {
      this.show = true;
      this.load();
    },
    async load(filterData, page) {
      this.loading = true;
      if (page) {
        this.pageInfo.currentPage = Number(page);
      }
      if (!filterData) {
        filterData = {};
      }
      const pageInfo = {
        pageSize: this.pageInfo.pageSize,
        pageIndex: this.pageInfo.currentPage,
      };
      const { url, paramsType, defaultParams, jsonParams } =
        this.config.dialogContent.contentRequest;
      let params = {};
      if (paramsType === "string") {
        let paramStr = "";
        Object.keys(jsonParams).forEach((key) => {
          paramStr += `${key}:${jsonParams[key]};`;
        });
        params = { ...defaultParams, paramStr, pageInfo };
      } else {
        params = { ...defaultParams, ...filterData, pageInfo };
      }
      let res = await http({
        url: url,
        methods: "post",
        data: params,
      });
      if (res.code == 200) {
        const { meta } = res;
        if (meta.resList) {
          this.config.dialogContent.tableData = meta.resList.executeSqlResps;
          this.pageInfo.total = Number(meta.resList.pageInfo.rowCount);
        } else if (meta.returnJson) {
          this.config.dialogContent.tableData = meta.returnJson;
        } else if (meta.returnObj) {
          this.config.dialogContent.tableData = meta.returnObj;
        } else if (meta.resultObject) {
          this.config.dialogContent.tableData = meta.resultObject.customers;
          this.pageInfo.total = Number(meta.resultObject.pageInfo.rowCount);
        }
      } else {
        this.$message.error("列表接口报错");
      }
      this.loading = false;
    },
    //搜素表单中的select的options选项，要求tableForm.items数组中如果有select,则排在数组的前面，
    // optionRequests 数组中对应的写select的options的请求地址及参数,且option的接口数据是：[{text,value}]
    async querySelectOptions() {
      if (!this.config.dialogContent.optionRequests.length) {
        return;
      }
      const requests = this.config.dialogContent.optionRequests.map((item) => {
        return http({ url: item.url, data: item.defaultParams });
      });
      const results = Promise.all(requests);
      this.$attrs.tableForm.items.forEach((item, i) => {
        if (item.itemRender.name == "$select") {
          item.itemRender.options = results[i].meta.returnJson;
        }
      });
    },
    async getrow(row) {
    //客户规则埋点
      var ruleParam = [{
        "PUB_REQ": {
          "TYPE": "GOVCRM.ORDERSET.localCust"
        },
        "CUST": {
          "CUST_ID": row.custId + ""
        },
        "ORDCOMMON": {
          "STAFF_ID": this.user.staffId + "",
          "ORG_ID": this.user.orgId + ""
        }
      }];
      //调用规则平台
      const result = await OrderService.rulePlatfromCheck(ruleParam);
      let ruleCode = result.code;
      let ruleMsg = result.msg;
      //直接通过校验
      if (ruleCode == 0) {
        //直接校验通过继续之前逻辑
        this.formData[this.key].value =
          row[this.config.dialogContent.submitKey];
        this.formData[this.key].text =
          row[this.config.dialogContent.showKey];
        this.showValue = row[this.config.dialogContent.showKey];
        this.$emit("input", row[this.config.dialogContent.submitKey]);
        this.$emit("getPluginValue", { value: row, key: this.key });
        this.$store.commit("orders/SET_CUST_INFO_CHANGE", row);
        this.show = false;
      } else {
        //校验结果有警告或者拒绝，弹窗提示
        //图标样式
        let iconType = 'warning';
        if (ruleCode == 2) {
          iconType = 'error';
        }
        this.$confirm(ruleMsg, '提示', {
          confirmButtonText: '确定',
          type: iconType
        }).then(() => {
          //不是拒绝执行（提醒或异常）
          if (ruleCode != 2) {
            //继续之前逻辑
            this.formData[this.key].value =
              row[this.config.dialogContent.submitKey];
            this.formData[this.key].text =
              row[this.config.dialogContent.showKey];
            this.showValue = row[this.config.dialogContent.showKey];
            this.$emit("input", row[this.config.dialogContent.submitKey]);
            this.$emit("getPluginValue", { value: row, key: this.key });
            this.$store.commit("orders/SET_CUST_INFO_CHANGE", data.row);
            this.show = false;
          }
        }).catch(() => {

        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.hide {
  z-index: 0;
  visibility: hidden;
  width: 1px;
  position: absolute;
}
.empty {
  height: 80px;
}
.el-icon-more {
  font-size: 20px;
}
.click-wrap {
  ::v-deep .el-input-group--append .el-input__inner,
  .el-input-group__prepend {
    cursor: pointer;
  }
}
</style>